var express = require("express");
var router = express.Router();
const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();

/* 获取点赞数 */
router.get("/num", async (req, res) => {
  const { topic_id, topic_type } = req.query;

  const like_num = await prisma.num_like.findFirst({
    where: {
      topic_id: topic_id,
      topic_type: parseInt(topic_type),
    },
  });

  res.json(like_num == null ? 0 : like_num.num);
});

/* 判断用户是否点赞 */
router.get("/", async (req, res) => {
  const { topic_id, topic_type } = req.query;

  const like = await prisma.user_like.findMany({
    where: {
      topic_id: topic_id,
      topic_type: parseInt(topic_type),
      user_id: req.auth.user.user_id,
    },
  });

  res.json(like.length >= 1);
});

/* 切换用户点赞状态  */
router.post("/change", async (req, res) => {
  const { topic_id, topic_type } = req.body;

  //获取点赞状态
  const like = await prisma.user_like.findMany({
    where: {
      topic_id: topic_id,
      topic_type: parseInt(topic_type),
      user_id: req.auth.user.user_id,
    },
  });

  //获取点赞数
  const like_num = await prisma.num_like.findFirst({
    where: {
      topic_id: topic_id,
      topic_type: parseInt(topic_type),
    },
  });

  //用户取消点赞
  if (like.length >= 1) {
    //删除用户点赞记录
    const like_delete = await prisma.user_like.deleteMany({
      where: {
        topic_id: topic_id,
        topic_type: parseInt(topic_type),
        user_id: req.auth.user.user_id,
      },
    });
    //点赞数-1
    const num_decre = await prisma.num_like.updateMany({
      where: { topic_id: topic_id, topic_type: parseInt(topic_type) },
      data: {
        num: {
          decrement: 1,
        },
      },
    });
    res.json(like_num == null ? 0 : like_num.num - 1);
  }
  //用户点赞
  else {
    //新增用户点赞记录
    const new_like = await prisma.user_like.create({
      data: { topic_id: topic_id, topic_type: parseInt(topic_type), user_id: req.auth.user.user_id },
    });
    //点赞数+1
    if (like_num == null) {
      const new_like_num = await prisma.num_like.create({
        data: { topic_id: topic_id, topic_type: parseInt(topic_type), num: 1 },
      });
    } else {
      const num_incre = await prisma.num_like.updateMany({
        where: { topic_id: topic_id, topic_type: parseInt(topic_type) },
        data: {
          num: {
            increment: 1,
          },
        },
      });
    }
    //返回点赞数
    res.json(like_num == null ? 1 : like_num.num + 1);
  }
});

module.exports = router;
